package json

import java.io.IOException

import org.json.JSONObject
import org.scalameter.{Bench, Gen}
import org.scalameter.api._

import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper}
import com.google.gson.{JsonElement, JsonParser}

object JsonParseScalaMeter extends Bench.OfflineReport {

  val mapper = new ObjectMapper
  val s =
    "{\"type\":\"duration\",\"sub_type\":\"concrete\",\"start\":\"2019-09-10T05:00:00\",\"end\":\"2019-09-10T17:00:00\",\"grain\":\"arbitrary\",\"festival_flag\":false,\"token\":\"明天上午五点到下午五点\",\"start_timestamp\":1568062800000,\"end_timestamp\":1568106000000}"

  @throws[IOException]
  def jackson(): JsonNode = mapper.reader.readTree(s)

  def orgJson(): JSONObject = {
    val node = new JSONObject(s)
    node
  }

  def gson(): JsonElement = JsonParser.parseString(s)

  // Generator
  val gen = Gen.unit("fixed")

  //DSL - group
  performance of "Json parse (non-databind)" in {
    measure method "jackson" in {
      using(gen) config (exec.benchRuns -> 10) in { _ =>
        for (_ <- 1 to 10000) jackson()
      }
    }

    measure method "gson" in {
      using(gen) config (exec.benchRuns -> 10) in { _ =>
        for (_ <- 1 to 10000) gson()
      }
    }

    measure method "org.json" in {
      using(gen) config (exec.benchRuns -> 10) in { _ =>
        for (_ <- 1 to 10000) orgJson()
      }
    }
  }
}
